package com.tensquare.notice.service;
/*
 *ClassName:NoticeService
 *Description:
 *@author:可爱的大鸭子
 */

import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.baomidou.mybatisplus.plugins.Page;
import com.netflix.discovery.converters.Auto;
import com.tensquare.notice.client.ArticleClient;
import com.tensquare.notice.client.CommentClient;
import com.tensquare.notice.client.UserClient;
import com.tensquare.notice.dao.NoticeDao;
import com.tensquare.notice.dao.NoticeFreshDao;
import com.tensquare.notice.pojo.Notice;
import com.tensquare.notice.pojo.NoticeFresh;
import entity.Result;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import util.IdWorker;

import javax.xml.stream.events.Comment;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service
public class NoticeService {
    @Autowired
    private NoticeDao noticeDao;
    @Autowired
    private NoticeFreshDao noticeFreshDao;
    @Autowired
    private IdWorker idWorker;
    @Autowired
    private ArticleClient articleClient;
    @Autowired
    private UserClient userClient;
    @Autowired
    private CommentClient commentClient;

    public Notice selectById(String id) {
        Notice notice=noticeDao.selectById(id);
        //完善通知消息
        getNoticeInfo(notice);
        return notice;
    }

    public Page<Notice> selectByPage(Notice notice, Integer page, Integer size) {
        //封装分页对象
        Page<Notice> pageData = new Page<>(page, size);
        //执行分页查询.传入条件notice
        List<Notice> noticeList = noticeDao.selectPage(pageData, new EntityWrapper<>(notice));
        for (Notice n : noticeList) {
            getNoticeInfo(n);
        }
        //设置结果集到分页对象中
        pageData.setRecords(noticeList);
        //返回
        return pageData;
    }

    public String save(Notice notice) {
        //设置初始值
        //设置状态 0表示未读 1表示已读
        notice.setState("0");
        notice.setCreatetime(new Date());
        //使用分布式Id生成器，生成id
        String id = idWorker.nextId() + "";
        //新的消息入库
        notice.setId(id);
        noticeDao.insert(notice);
        return notice.getId();
        //待推送消息入库，新消息提醒，现在因为改进了所以用不到，将通知消息放入了rabbitMq中
        /*NoticeFresh noticeFresh = new NoticeFresh();
        noticeFresh.setNoticeId(id);//消息id
        noticeFresh.setUserId(notice.getReceiverId());//待通知用户的id，从前端分装好了已经
        noticeFreshDao.insert(noticeFresh);*/
    }

    public void updateById(Notice notice) {
        noticeDao.updateById(notice);
    }

    public Page<NoticeFresh> freshPage(String userId, Integer page, Integer size) {
        //封装查询条件
        NoticeFresh noticeFresh = new NoticeFresh();
        noticeFresh.setUserId(userId);
        //创建分页对象
        Page<NoticeFresh> pageData = new Page<>(page, size);
        //执行查询
        List<NoticeFresh> list = noticeFreshDao.selectPage(pageData, new EntityWrapper<>(noticeFresh));
        //设置查询结果集到分页对象中
        pageData.setRecords(list);
        //返回结果
        return pageData;
    }

    public void freshDelete(NoticeFresh noticeFresh) {
        noticeFreshDao.delete(new EntityWrapper<>(noticeFresh));
    }

    //获取消息的具体内容数据
    private void getNoticeInfo(Notice notice) {
        //根据消息通知里的用户id获取用户信息
        Result userResult = userClient.findById(notice.getOperatorId());
        HashMap userMap = (HashMap) userResult.getData();
        notice.setOperatorName(userMap.get("nickname").toString());
        //获取文章信息
        if ("article".equals(notice.getTargetType())) {
            Result articleResult = articleClient.findById(notice.getTargetId());
            HashMap articleMap = (HashMap) articleResult.getData();
            notice.setTargetName(articleMap.get("title").toString());
        }
    }

    //删除指定的消息通知
    public void delete(Notice notice) {
        Map<String,Object> map = new HashMap<>();
        map.put("receiverId",notice.getReceiverId());
        map.put("operatorId",notice.getOperatorId());
        map.put("action",notice.getAction());
        noticeDao.deleteByMap(map);
    }

    //查询当前登录用户所有未读的消息通知
    public List<Notice> findAllNotices(String userId) {
        EntityWrapper wrapper = new EntityWrapper<Notice>();
        wrapper.eq("receiverId",userId);
        wrapper.eq("state","0");
        wrapper.orderBy("createtime",false);
        List<Notice> list= noticeDao.selectList(wrapper);
        for(Notice notice:list){
            //设置发送消息的人的名字
            Result result = userClient.findById(notice.getOperatorId());
            HashMap<String,Object> userMap = (HashMap)result.getData();
            notice.setOperatorName((String)userMap.get("nickname"));
            //设置操作名称
            String action=notice.getAction();
            if(action.equals("thumbup")){
                notice.setActionName("点赞了你的");
            }
            else if(action.equals("subscribe")){
                notice.setActionName("订阅了你");
            }
            else if(action.equals("publish")){
                notice.setActionName("发布了新");
            }
            else if(action.equals("comment")){
                notice.setActionName("评论了你的");
            }
            else if(action.equals("love")){
                notice.setActionName("喜欢了你的");
            }
            //设置操作对象
            String targetType=notice.getTargetType();
            if(targetType.equals("article")){
                String targetId=notice.getTargetId();
                HashMap articleMap=(HashMap)articleClient.findById(targetId).getData();
                 notice.setTargetName((String)articleMap.get("title"));
                 notice.setActionName(notice.getActionName()+"文章");
            }
            else if(targetType.equals("comment")){
                String targetId=notice.getTargetId();
                HashMap commentMap=(HashMap)commentClient.findById(targetId).getData();
                notice.setTargetName((String)commentMap.get("content"));
                notice.setActionName(notice.getActionName()+"评论");
            }
            else if(targetType.equals("gath")){
                String targetId=notice.getTargetId();
                notice.setActionName(notice.getActionName()+"约会");
            }
        }
        return list;
    }

    //设置某条消息已读
    @Transactional
    public void setReaded(String nid) {
        Notice notice=noticeDao.selectById(nid);
        notice.setState("1");
        noticeDao.updateById(notice);
    }

    //设置某用户的未读消息全部已读
    @Transactional
    public void setAllReaded(String uid) {
        EntityWrapper wrapper = new EntityWrapper<Notice>();
        wrapper.eq("receiverId",uid);
        wrapper.eq("state","0");
        List<Notice> list= noticeDao.selectList(wrapper);
        for(Notice notice:list){
            notice.setState("1");
            noticeDao.updateById(notice);
        }
    }

    //获取我的未读消息的数量
    public int getMyMessNum(String userId) {
        EntityWrapper wrapper = new EntityWrapper<Notice>();
        wrapper.eq("receiverId",userId);
        wrapper.eq("state","0");
        Integer integer = noticeDao.selectCount(wrapper);
        return integer.intValue();
    }
}
